package com.ucode.springboot.ueditor.baidu.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;

import com.ucode.springboot.starter.fileStorage.FsClient;
import com.ucode.springboot.starter.fileStorage.FsProviderType;
import com.ucode.springboot.starter.fileStorage.UploadResult;
import com.ucode.springboot.ueditor.baidu.define.AppInfo;
import com.ucode.springboot.ueditor.baidu.define.BaseState;
import com.ucode.springboot.ueditor.baidu.define.FileType;
import com.ucode.springboot.ueditor.baidu.define.State;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class StorageManager {
    
    private static Log log = LogFactory.get();
    
    public static FsProviderType fsProviderType = FsProviderType.qiniu;
    public static String clientId = "1";
    
    public static final int BUFFER_SIZE = 8192;
    
	public static State saveBinaryFile(byte[] data, String path){
	    
	    log.info("二进制上传的文件path:"+path);
	    
	    UploadResult uploadResult = FsClient.getClient(fsProviderType,clientId).upload(path, data);
	    if(uploadResult == null){
            return new BaseState(false);
        }
	    State state = new BaseState(true);
        state.putInfo("size", data.length);
        state.putInfo("title", path);
        state.putInfo("url", uploadResult.getUrlprefix() + uploadResult.getFilePath());
	    return state;
	}

	public static State saveFileByInputStream(InputStream is, String path,long maxSize) {
	    File tmpFile = getTmpFile();
	    byte[] dataBuf = new byte[ 2048 ];
	    BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
	    try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
            int count = 0;
            while ((count = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, count);
            }
            bos.flush();
            bos.close();

            if (tmpFile.length() > maxSize) {
                tmpFile.delete();
                return new BaseState(false, AppInfo.MAX_SIZE);
            }

            State state = saveTmpFile(tmpFile, path);

            if (!state.isSuccess()) {
                tmpFile.delete();
            }

            return state;
            
        } catch (IOException e) {
        }
	    return new BaseState(false, AppInfo.IO_ERROR);
	}

	public static State saveFileByInputStream(InputStream is, String path) {
	    State state;
        File tmpFile = getTmpFile();
        byte[] dataBuf = new byte[ 2048 ];
        BufferedInputStream bis = new BufferedInputStream(is, StorageManager.BUFFER_SIZE);
        try {
            BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(tmpFile), StorageManager.BUFFER_SIZE);
            int count = 0;
            while ((count = bis.read(dataBuf)) != -1) {
                bos.write(dataBuf, 0, count);
            }
            bos.flush();
            bos.close();
            state = saveTmpFile(tmpFile, path);
            if (!state.isSuccess()) {
                tmpFile.delete();
            }
            return state;
        } catch (IOException e) {
        }
        return new BaseState(false, AppInfo.IO_ERROR);
	}
	

    private static State saveTmpFile(File tmpFile, String path) {
        
        log.info("文件流上传的文件path:"+path);
        
        UploadResult uploadResult = FsClient.getClient(fsProviderType,clientId).upload(path, tmpFile);
        if(uploadResult == null){
            return new BaseState(false);
        }
        State state = new BaseState(true);
        state.putInfo("size", tmpFile.length());
        state.putInfo("title", path);
        state.putInfo("url", uploadResult.getUrlprefix() + uploadResult.getFilePath());
        return state;
    }
	
	private static File getTmpFile() {
		File tmpDir = FileUtils.getTempDirectory();
		String tmpFileName = (Math.random() * 10000 + "").replace(".", "");
		return new File(tmpDir, tmpFileName);
	}

	
	private static String getFileName(String fileName) {
		String suffix =  FileType.getSuffixByFilename(fileName);
		return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+ (int)(Math.random()*9000 +1000) + suffix;
	}
}
